package com.example.plcopne.ui

import android.os.Bundle
import com.example.plcopne.R
import com.example.plcopne.db.DataDb
import kotlinx.android.synthetic.main.activity_data_test.*
import org.litepal.LitePal

class DataTestActivity : BaseActivity() {
    override fun getContentView(): Int {
        return R.layout.activity_data_test
    }

    var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"


    var strLogs = ""
    override fun init(savedInstanceState: Bundle?) {
        settitle("数据库测试")


        btn_writedata.setOnClickListener {
            val joinToString = (1..8).map {
                str.random()
            }.joinToString("")
            var dataDb = DataDb()
            dataDb.name = joinToString
            try {
                dataDb.saveThrows()
                addLog("写入成功")
                addLog("写入数据为:$joinToString")
            } catch (e: Exception) {
                edtLog.setText("写入失败${e.message}")
                edtLog.setSelection(edtLog.text.length)
            }


        }
        btn_readdata.setOnClickListener {
            val findLast = LitePal.findLast(DataDb::class.java)
            findLast?.let {

                addLog("读取成功:${it.name}")
            }



        }

        btn_clear.setOnClickListener {
            val findAll = LitePal.findAll(DataDb::class.java)
            findAll.forEach {
                it.delete()
            }
            edtLog.setText("")
            edtLog.setSelection(edtLog.text.length)

        }

    }


    fun addLog(msg:String) {
        strLogs = edtLog.text.toString().trim()
        strLogs += "\r\n $msg"


        edtLog.setText(strLogs)
        edtLog.setSelection(edtLog.text.length)

    }

}